package git.soulbgm.service.impl;

import git.soulbgm.common.base.BaseServiceImpl;
import git.soulbgm.mapper.AccountMapper;
import git.soulbgm.pojo.Account;
import git.soulbgm.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 账户表
 *
 * @author SoulBGM
 * @version V1.0
 * @date 2020-11-06 17:27:16
 */
@Service
public class AccountServiceImpl extends BaseServiceImpl<AccountMapper, Account> implements AccountService {

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public boolean reduceBalance(Long accountId, Double price) throws Exception {
        Account account = findById(accountId);
        // 检查余额
        checkInventory(account, price);
        // 扣减金额
        account.setBalance(account.getBalance() - price);
        return update(account);
    }

    private void checkInventory(Account account, Double price) throws Exception {
        Double balance = account.getBalance();
        if (balance < price) {
            throw new Exception("余额不足");
        }
    }
}